package com.example.c_reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Test {
    public static void main(String[] args) {
//        get1();

        System.out.println("=========================");
        Class<Person> personClass = Person.class;
//        获取所有public的构造方法，不到private私有方法
        Constructor<?>[] constructors = personClass.getConstructors();
        for (Constructor<?> constructor : constructors) {
            System.out.println(constructor);
        }

        System.out.println("=========================");
        Constructor<Person> constructor = null;
        try {
            constructor = personClass.getConstructor();
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
        System.out.println("constructor:" + constructor);

        System.out.println("=========================");
        Person person = null;
        try {
//            调用时，要求是public的无参构造方法
            person = constructor.newInstance();
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        System.out.println("person: " + person);
    }

    public static void get1() {
//        1、调用getClass
        Person person = new Person();
        Class<? extends Person> aClass = person.getClass();
        System.out.println("Class name: " + aClass);

        
        System.out.println("=====================");
        Class<Person> personClass = Person.class;
        System.out.println("personClass Class name: " + personClass);

        System.out.println("=====================");
        Class<?> aClass1 = null;
        try {
            aClass1 = Class.forName("com.example.c_reflect.Person");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        System.out.println("aClass1 Class name: " + aClass1);

        System.out.println("是否相等: " + (aClass == personClass));
    }
}

